package com.suke.czx.modules.tb.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suke.czx.modules.tb.entity.TbOrderInfo;
import com.suke.czx.modules.tb.vo.MessageHeadVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import com.suke.czx.modules.tb.mapper.TbMessageMapper;
import com.suke.czx.modules.tb.entity.TbMessage;
import com.suke.czx.modules.tb.service.TbMessageService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户消息私信表
 *
 * @author developer
 * @email developer@163.com
 * @date 2025-05-20 18:48:09
 */
@Service
public class TbMessageServiceImpl extends ServiceImpl<TbMessageMapper, TbMessage> implements TbMessageService {

    @Override
    public List<MessageHeadVO> getMessageHeadList(String userId, Map<String, Object> params) {
        List<MessageHeadVO> messageHeadList = baseMapper.getMessageHeadList(userId, params);
        if (CollectionUtils.isNotEmpty(messageHeadList)) {
            List<MessageHeadVO> lastMessages = null;
            for (MessageHeadVO messageHeadVO : messageHeadList) {
                lastMessages = baseMapper.getLastMessageList(messageHeadVO);
                if (CollectionUtils.isNotEmpty(lastMessages)) {
                    messageHeadVO.setLastMessageTime(lastMessages.get(0).getLastMessageTime());
                    messageHeadVO.setContent(lastMessages.get(0).getContent());
                }
            }
        }
        return messageHeadList;
    }

    @Override
    public boolean sendOrderMessage(TbOrderInfo tbOrderInfo,  String contentType) {
        TbMessage tbMessage = new TbMessage();
        // 已发货
        if ("orderShipped".equals(contentType)) {
            tbMessage.setSenderId(tbOrderInfo.getSellerId());
            tbMessage.setReceiverId(tbOrderInfo.getBuyerId());
        }else{
            tbMessage.setSenderId(tbOrderInfo.getBuyerId());
            tbMessage.setReceiverId(tbOrderInfo.getSellerId());
        }
        tbMessage.setProductId(tbOrderInfo.getProductId());
        tbMessage.setIsRead(0);
        tbMessage.setContentType(contentType);
        tbMessage.setCreateDate(new Date(System.currentTimeMillis()));
        tbMessage.setContent(JSONUtil.toJsonStr(tbOrderInfo));
        return this.save(tbMessage);
    }

    @Override
    public boolean setDeafultHeadMessage(Long productId, String userId, String receiverId, Date date) {
        LambdaQueryWrapper<TbMessage> tmlqw = new LambdaQueryWrapper<>();
        tmlqw.eq(TbMessage::getProductId, productId);
        tmlqw.and(and->and.eq(TbMessage::getSenderId, userId).or().eq(TbMessage::getReceiverId, receiverId));
        long count = baseMapper.selectCount(tmlqw);
        // 如果 count === 0 则是第一次，创建head对话
        if(count == 0){
            try{
                TbMessage tbMessage1 = new TbMessage();
                tbMessage1.setSenderId(userId);
                tbMessage1.setReceiverId(receiverId);
                tbMessage1.setContentType("head");
                tbMessage1.setProductId(productId);
                tbMessage1.setCreateDate(date);
                baseMapper.insert(tbMessage1);
                TbMessage tbMessage2 = new TbMessage();
                tbMessage2.setSenderId(receiverId);
                tbMessage2.setReceiverId(userId);
                tbMessage2.setContentType("head");
                tbMessage2.setProductId(productId);
                tbMessage2.setCreateDate(date);
                baseMapper.insert(tbMessage2);

            }catch(Exception e){
                log.error("创建head对话失败", e);
                return false;
            }
        }
        return true;
    }
}
